package com.woniu.zsd.platform.Netty;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.platform.model.ChatMessage;
import com.woniu.zsd.platform.service.impl.ChatMessageService;
import com.woniu.zsd.platform.service.impl.ChatRecordService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;


public class WebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Resource
    private ChatMessageService chatMessageService;

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static ConcurrentHashMap<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        channels.remove(ctx.channel());
        userChannelMap.values().remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws JsonProcessingException {
        String messageText = msg.text();
        System.out.println("收到消息：" + messageText);

        // 先检查消息是否为空
        if (messageText == null || messageText.trim().isEmpty()) {
            System.out.println("收到空消息，忽略");
            return;  // 可以选择返回给客户端一个错误消息
        }

        ChatMessage chatMessage;
        try {
            // 尝试解析 JSON 数据
            chatMessage = objectMapper.readValue(messageText, ChatMessage.class);
        } catch (JsonProcessingException e) {
            // 捕获 JSON 解析异常并输出错误日志
            System.out.println("消息格式错误: " + messageText);
            e.printStackTrace();

            // 向客户端发送错误信息 (可选)
            ctx.channel().writeAndFlush(new TextWebSocketFrame("消息格式错误，请检查输入的数据格式"));
            return;
        }

        // 处理不同类型的消息
        if ("register".equals(chatMessage.getType())) {
            // 处理注册逻辑
            userChannelMap.put(chatMessage.getSender(), ctx.channel());
            System.out.println(chatMessage.getSender() + " 已连接 WebSocket");
            return;
        }

        // 处理私聊消息
        handlePrivateChat(chatMessage);
    }

    /**
     * 处理一对一私聊消息
     */
    private void handlePrivateChat(ChatMessage chatMessage) {
        String receiverId = chatMessage.getReceiver();

        // 检查 receiverId 是否有效
        if (receiverId == null || receiverId.trim().isEmpty()) {
            System.out.println("无效的接收者 ID: " + receiverId);
            return;
        }

        Channel receiverChannel = userChannelMap.get(receiverId);

        if (receiverChannel != null) {
            // 如果接收者在线，发送消息
            receiverChannel.writeAndFlush(new TextWebSocketFrame(chatMessage.getSender() + ": " + chatMessage.getContent()));
        } else {
            // 如果接收者不在线，将消息存储到 Redis
            System.out.println("用户 " + receiverId + " 不在线，消息存入 Redis");
            chatMessageService.saveMessage(chatMessage);  // 存入 Redis
        }

        // 存储消息记录，存入 Redis 或数据库（具体取决于您的存储需求）
        System.out.println(chatMessage);
        chatMessageService.saveMessage(chatMessage); // 存入 Redis
    }


    /**
     * 广播消息给所有连接的客户端
     */
    public static void broadcast(String message) {
        channels.writeAndFlush(new TextWebSocketFrame(message));
    }
}
